function [image_data,signal_rand,signal] = spike_triggered_pixelmap(frame_times, spike_times, imagestack)

%%input: frame_times, spike_times, scanrate, imagestack(x,y,t)

%imagestack=int16(imagestack);

cut = max(find(spike_times<frame_times(length(frame_times)-50)));

for ind = 1:cut
    spike_frames(ind) = min(find(frame_times > spike_times(ind)));
end

cnt=0;
post_frames = 10;
pre_frames = 10;
for ind = 1:cut
    signal_ind_post(1+cnt*post_frames:10+cnt*post_frames) = spike_frames(ind):spike_frames(ind)+post_frames-1;
    signal_ind_pre(1+cnt*pre_frames:10+cnt*pre_frames) = spike_frames(ind)-pre_frames:spike_frames(ind)-1;
    cnt=cnt+1;
end

signal = zeros(size(imagestack,1),size(imagestack,2));
signal = mean(imagestack(:,:,signal_ind_post),3)-mean(imagestack(:,:,signal_ind_pre),3);

win_size=4;
signal_smoothed = filter2(ones(win_size)/win_size^2,signal);
signal_smoothed(signal_smoothed<prctile(signal_smoothed(:),80))=0;

figure;
imagesc(signal);
title('raw spike triggered pixelmap')

figure;
clf; colormap gray
image_data=zeros(size(imagestack,1),size(imagestack,2),3);
image_data(:,:,2)=(mean(imagestack,3)/max(max(mean(imagestack,3))));
image_data(:,:,1)=signal_smoothed/max(signal_smoothed(:));
image(image_data)
title('smoothed spike triggered pixelmap on template')


last_spike_frame=spike_frames(end);
signal_rand = zeros(size(imagestack,1),size(imagestack,2),100);

% for knd=1:100
%     spike_frames=ceil(rand(cut,1)*last_spike_frame);
%     cnt=0;
%     for ind = 1:cut
%         signal_ind(1+cnt*post_frames:10+cnt*post_frames) = spike_frames(ind):spike_frames(ind)+post_frames-1;
%         cnt=cnt+1;
%     end
%     signal_rand(:,:,knd) = mean(imagestack(:,:,signal_ind),3)-mean(imagestack(:,:,setdiff([1:size(imagestack,3)],signal_ind)),3);
% end

1;



